<template>
	<view>
		<nav-header left-icon-color="white" :title="title" :show-right="false" bg-color="transparent" :fixed="false"
			:show-border="false"></nav-header>
		<scroll-view class="scroll-content" scroll-y>
			<uni-forms border ref="form" :rules="rules" :modelValue="formData" label-width="80px">
				<view class="transfer-header">
					<view v-if="type==='Withdrawal'">
						<uni-forms-item required label="真实姓名" name="realName">
							<uni-easyinput v-model="formData.realName" placeholder="请输入真实姓名"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item required label="身份证" name="idCardLast6">
							<uni-easyinput v-model="formData.idCardLast6" placeholder="请输入身份证后6位"></uni-easyinput>
						</uni-forms-item>
						<text class="warning">注:根据提现规定，需提供账号对应的真实姓名以及身份证后6位，谢谢配合</text>
					</view>
					<text v-if="type==='Pay'">充值金额</text>
					<view v-else-if="type==='Withdrawal'" class="header">
						<text>当前钱包余额为￥{{walletInfo.balanceFee}}</text>
						<text class="all" @tap="allWithDrawal">全部提现</text>
					</view>
					<view>
						<view class="input-container" v-if="type==='Pay'">
							<view class="prefix">￥</view>
							<input class="input" type="digit" required v-model="money" placeholder="请输入金额" />

						</view>
						<view class="input-container" v-else-if="type==='Withdrawal'">
							<view class="prefix">￥</view>
							<input class="input" type="digit" required v-model="money" @input="handleInput"
								@blur="validate" placeholder="请输入余额" />
						</view>
					</view>
				</view>
				<view class="transfer-way">
					<text v-if="type==='Pay'">支付方式</text>
					<text v-else-if="type==='Withdrawal'">提现方式</text>
					<view class="way" @click="selectPayMethod('wxpay')" v-if="type==='Pay'">
						<view class="way-left">
							<svg-icon icon="wxpay" :width="70"></svg-icon>
							<text>微信支付</text>
							<!-- <text v-else-if="type==='Withdrawal'">微信钱包</text> -->
						</view>
						<view class="way-right">
							<!-- #ifdef H5 || APP-PLUS -->
							<radio :checked="selectedPayMethod==='wxpay'" @click="selectPayMethod('wxpay')"></radio>
							<!-- #endif -->
							<!-- #ifndef H5 || APP-PLUS-->
							<radio :checked="selectedPayMethod==='wxpay'"></radio>
							<!-- #endif -->
						</view>
					</view>
					<view class="way" @click="selectPayMethod('alipay')" v-if="type=='Withdrawal'">
						<view class="way-left">
							<svg-icon icon="alipay" :width="70"></svg-icon>
							<text v-if="type==='Pay'">支付宝支付</text>
							<text v-else-if="type==='Withdrawal'">支付宝</text>
						</view>
						<view class="way-right">
							<radio :checked="selectedPayMethod==='alipay'" disabled v-if="type=='Pay'"></radio>
							<radio :checked="selectedPayMethod==='alipay'" v-else-if="type=='Withdrawal'"></radio>
						</view>
					</view>
					<uni-forms-item required label="账户" name="account" v-if="selectedPayMethod==='alipay'">
						<uni-easyinput v-model="formData.account" placeholder="请输入支付宝账户"></uni-easyinput>
					</uni-forms-item>
					<view class="way" v-if="type==='Withdrawal'" @click="selectPayMethod('bank')">
						<view class="way-left">
							<svg-icon icon="银行卡管理" :width="75"></svg-icon>
							<text>银行卡</text>
						</view>
						<view class="way-right">
							<radio :checked="selectedPayMethod==='bank'"></radio>
						</view>
					</view>
					<uni-forms-item required label="所属银行" name="bankName" v-if="selectedPayMethod==='bank'">
						<uni-easyinput v-model="formData.bankName" placeholder="请输入银行卡名称"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item required label="银行卡" name="bankAccount" v-if="selectedPayMethod==='bank'">
						<uni-easyinput v-model="formData.bankAccount" placeholder="请输入银行卡账户"></uni-easyinput>
					</uni-forms-item>
				</view>
			</uni-forms>
		</scroll-view>
		<tabbar-button-group text="确认充值" @click="payMoney" v-if="type==='Pay'"></tabbar-button-group>
		<tabbar-button-group text="确认提现" @click="takeMoney" v-else-if="type==='Withdrawal'"></tabbar-button-group>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				type: null,
				title: "",
				formData: {
					realName: "",
					idCardLast6: "",
					account: "",
					platform: 0,
					bankName: "",
					bankAccount: ""
				},
				rules: {
					realName: {
						rules: [{
								required: true,
								errorMessage: '请填写姓名',
							},
							{
								minLength: 2,
								maxLength: 10,
								errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符',
							},
							{
								pattern: /^[\u4e00-\u9fa5]+$/, // 只允许中文
								errorMessage: '姓名只能包含中文',
							}
						],
					},
					idCardLast6: {
						rules: [{
								required: true,
								errorMessage: '请填写身份证后6位',
							},
							{
								pattern: /^\d{6}$/,
								errorMessage: '请输入正确的身份证后6位数字',
							}
						],
					},
					account: {
						rules: [{
								required: true,
								errorMessage: '请填写支付宝账户',
							},
							{
								pattern: /^(?:\d{11}|\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)$/, //支持手机号和邮箱格式
								errorMessage: '请输入正确的支付宝账户（手机号或邮箱）',
							}
						],
					},
					bankName: {
						rules: [{
								required: true,
								errorMessage: '请填写银行卡名称',
							},
							{
								pattern: /^[\u4e00-\u9fa5]+$/, // 只允许中文
								errorMessage: '银行卡名称只能包含中文',
							}
						],
					},
					bankAccount: {
						rules: [{
								required: true,
								errorMessage: '请填写银行卡账户',
							},
							{
								pattern: /^\d{16,19}$/,
								errorMessage: '请输入正确的银行卡号',
							}
						],
					}
				},
				walletInfo: {}, //钱包信息
				selectedPayMethod: null, // 当前选中的支付方式
				money: null,
				errorMessage: null
			}
		},
		computed: {
			// validate() {
			// 	if (this.money > this.walletInfo.balanceFee) {
			// 		uni.showToast({
			// 			title: "输入余额不能大于钱包余额",
			// 			icon: "none"
			// 		})
			// 		return this.money = null
			// 	}
			// }
		},
		methods: {
			// 选择支付方式
			selectPayMethod(method) {
				if (this.selectedPayMethod == method) {
					this.selectedPayMethod = null
					return
				}
				this.selectedPayMethod = method;
				if (this.selectedPayMethod === 'alipay') {
					if (this.type === 'Pay') {
						uni.showToast({
							title: "敬请期待，请选择微信支付",
							icon: "none"
						})
						this.selectedPayMethod = null
					}
				}
			},
			// 处理输入事件
			handleInput(event) {
				// 过滤非法字符（如负数、多个小数点等）
				let value = event.detail.value;
				value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
				value = value.replace(/(\..*)\./g, '$1'); // 只允许一个小数点
				this.money = value;
			},
			// 校验金额
			validate() {
				const money = parseFloat(this.money); // 将输入值转为数字

				// 校验是否为空
				if (!money) {
					uni.showToast({
						title: '请输入金额',
						icon: 'none',
					});
					this.money = ''; // 清空输入
					return;
				}

				// 校验是否为负数
				if (money < 0) {
					uni.showToast({
						title: '金额不能为负数',
						icon: 'none',
					});
					this.money = ''; // 清空输入
					return;
				}

				// 校验是否超过钱包余额
				if (money > this.walletInfo.balanceFee) {
					uni.showToast({
						title: '输入金额不能大于钱包余额',
						icon: 'none',
					});
					this.money = ''; // 清空输入
					return;
				}

				// 校验小数位数
				const decimalPart = (this.money.toString().split('.')[1] || '').length;
				if (decimalPart > 2) {
					uni.showToast({
						title: '金额最多支持两位小数',
						icon: 'none',
					});
					this.money = ''; // 清空输入
					return;
				}

				// 校验通过
				console.log('金额校验通过:', money);
			},
			allWithDrawal() {
				if (this.walletInfo.balanceFee == 0) {
					uni.showToast({
						title: "钱包余额为空，快去充值吧！",
						icon: "none"
					})
				} else {
					this.money = this.walletInfo.balanceFee
				}
			},
			payMoney() {
				if (this.money == null) {
					uni.showToast({
						title: "请输入金额",
						icon: "none"
					})
				} else if (this.money <= 0 || isNaN(this.money)) {
					uni.showToast({
						title: "请输入正确的金额",
						icon: "none"
					})
				} else {
					if (this.selectedPayMethod === 'wxpay') {
						//充值
						const self = this
						uni.showLoading({
							title: "正在请求资源"
						})
						wx.getUserInfo({
							//成功后会返回
							success: (userInfoRes) => {
								console.log(userInfoRes);
								wx.login({
									success(loginRes) {
										console.log(loginRes);
										if (loginRes.code) {
											self.$http({
												url: '/pay/wx/getOpenId', // 替换为您的实际 API 接口地址
												method: 'POST',
												data: {
													code: loginRes.code,
												},
											}).then(openidRes => {
												console.log(openidRes);
												uni.showLoading({
													title: "创建订单"
												})
												self.$http({
													url: '/pay/wx/recharge', // 替换为您的实际 API 接口地址
													method: 'POST',
													data: {
														openId: openidRes.openid,
														data: {
															amount: self.money * 100,
														}
													},
												}).then(orderRes => {
													uni.showLoading({
														title: "等待支付"
													})
													wx.requestPayment({
														timeStamp: orderRes
															.timeStamp + "",
														nonceStr: orderRes
															.nonceStr,
														signType: orderRes
															.signType,
														package: orderRes
															.prepayId,
														paySign: orderRes
															.paySign,
														success(res) {
															console.log(res);
															uni.showModal({
																title: "支付成功，请前往钱包查看",
																icon: 'success'
															})
														},
														// 失败回调
														fail(res) {
															console.log(res);
															uni.showModal({
																title: "支付失败，如您已经支付，请联系客服处理",
																icon: 'fail'
															})
														},
														// 接口调用结束回调
														complete() {
															uni.hideLoading()
														}
													})
												})
											})
										} else {
											console.log('登录失败！' + loginRes.errMsg)
										}
									}
								})
							}
						})
					} else if (this.selectedPayMethod == null) {
						uni.showToast({
							title: "请选择支付方式",
							icon: "error"
						})
					}
				}
			},
			takeMoney() {
				this.$refs.form.validate().then(res => {
					if (this.money == null) {
						uni.showToast({
							title: "请输入余额",
							icon: "none"
						})
					} else if (this.money <= 0 || isNaN(this.money)) {
						uni.showToast({
							title: "请输入正确的余额",
							icon: "none"
						})
					} else {
						if (this.selectedPayMethod == null) {
							uni.showToast({
								title: "请选择提现方式",
								icon: "error"
							})
						} else {
							if (this.selectedPayMethod === 'alipay') {
								this.formData.platform = 1
							} else if (this.selectedPayMethod === 'bank') {
								this.formData.platform = 2
								this.formData.account = this.formData.bankAccount
							}
							//提现
							const self = this
							uni.showLoading({
								title: "正在请求资源"
							})
							wx.getUserInfo({
								//成功后会返回
								success: (userInfoRes) => {
									console.log(userInfoRes);
									wx.login({
										success(loginRes) {
											console.log(loginRes);
											if (loginRes.code) {
												self.$http({
													url: '/pay/wx/getOpenId', // 替换为您的实际 API 接口地址
													method: 'POST',
													data: {
														code: loginRes.code,
													},
												}).then(openidRes => {
													console.log(openidRes);
													uni.showLoading({
														title: "创建订单"
													})
													self.$http({
														url: '/pay/wx/withdraw', // 替换为您的实际 API 接口地址
														method: 'POST',
														data: {
															openid: openidRes
																.openid,
															userinfo: userInfoRes,
															platform: self
																.formData
																.platform,
															account: self
																.formData
																.account,
															realName: self
																.formData
																.realName,
															idCardLast6: self
																.formData
																.idCardLast6,
															bankName: self
																.formData
																.bankName,
															totalAmount: self
																.money *
																100,

														},
													}).then(orderRes => {
														uni.showModal({
															title: "提现成功，请前往钱包查看",
															icon: 'success'
														})

													}).catch(err => {
														uni.showModal({
															title: "提现失败，请重新操作，如不行请联系客服处理",
															icon: 'fail'
														})
													})
													// 接口调用结束回调
													uni.hideLoading()
												})
											} else {
												console.log('登录失败！' + loginRes.errMsg)
											}
										}
									})
								}
							})
						}
					}
				}).catch(err => {
					uni.showToast({
						title: "请按照要求填入信息",
						icon: "none"
					})
				})
			},
			_getData() {
				this.$http({
					url: `/wallet/info`,
					method: 'GET'
				}).then(res => {
					console.log(res)
					this.walletInfo = res
					this.walletInfo.balanceFee = this.walletInfo.balanceFee.toFixed(2)
				})
			},
		},
		onLoad(options) {
			this.type = options.type
			this._getData()
			if (this.type === "Pay") {
				this.title = "充值"
			} else if (this.type === "Withdrawal") {
				this.title = "提现"
			}
		}
	}
</script>

<style lang="scss" scoped>
	.scroll-content {
		max-height: 80vh;
		overflow-y: auto;
	}

	.transfer-header {
		padding: 24rpx 32rpx;

		.warning {
			color: $error-500;
			font-size: 28rpx;
			margin-top: -20rpx;
		}

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 40rpx;

			.all {
				color: $brand-500;
			}
		}

		.input-container {
			display: flex;
			align-items: center;
			border-bottom: 1px solid #ccc;
			padding: 8px;
			margin-top: 20rpx;
		}

		.prefix {
			font-size: 24px;
			color: #333;
			font-weight: bold;
			margin-right: 8px;
		}

		.input {
			flex: 1;
			border: none;
			outline: none;
			font-size: 16px;
		}
	}

	.transfer-way {
		padding: 24rpx 32rpx;

		.way {
			border: 1rpx solid #dddddd;
			border-radius: 4px;
			padding: 16rpx 32rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;

			.way-left {
				display: flex;
				align-items: center;
				gap: 32rpx;
			}
		}
	}
</style>